package org.csu.mypetstore.controller;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import jdk.jfr.Registered;
import org.csu.mypetstore.domain.Account;
import org.csu.mypetstore.persistence.AccountMapper;
import org.csu.mypetstore.service.AccountService;
import org.csu.mypetstore.service.CatalogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

@Controller
@RequestMapping("/catalog")   //当前路径： templates/catalog
public class MainController {
    @Autowired
    private CatalogService catalogService;
    @Autowired
    private AccountMapper accountMapper;
    @Autowired
    private AccountService accountService;

    //完成top贴图中mainForm ,shopping，signon,signout,Myaccount,?，搜索等板块
    //vo类中的数据对应数据库表中的属性
    // vo层调用service层的方法，service层方法通过impl层来具体实现
    //impl层又调用mapper层
    // 通过添加attribute，将值映射到对应的html的标签中


    
    @GetMapping("mainForm")
    public String mainForm(HttpServletRequest request){
        String currentPath=request.getRequestURI();
        return "/catalog/main";}
    @GetMapping("/ShoppingCart")
    public String ShoppingCart(){return "/cart/cart";}

    @PostMapping("/SignonForm")
    public String SignonForm(@RequestParam("username") String username,
                             @RequestParam("password") String password,
                             @RequestParam("captcha") String inputCaptcha, // 新增验证码参数
                             Model model,
                             HttpSession session) {

        // 验证验证码
        String sessionCaptcha = (String) session.getAttribute("captcha");
        if (sessionCaptcha == null) {
            model.addAttribute("error", "验证为空");
            return "account/SignonForm";
        } else if (!sessionCaptcha.equalsIgnoreCase(inputCaptcha)) {
            model.addAttribute("error", "验证码错误");
            return "account/SignonForm";
        }

        if (accountService.login(username, password)) {
            // 登录成功后清除验证码
            session.removeAttribute("captcha");
            session.setAttribute("loginAccount",accountMapper.getAccountByUsername(username));
            session.setAttribute("username",username);
            model.addAttribute("username",username);
            return "catalog/main";
        } else {
            model.addAttribute("error", "用户名或密码错误");
            return "account/SignonForm";
        }

    }
    //验证码
    @GetMapping("/catalog/captcha")
    public void getCaptcha(HttpServletResponse response, HttpSession session) throws IOException {
        // 生成随机4位验证码
        String captcha = generateRandomCode(4);
        session.setAttribute("captcha", captcha);
        // 生成图片
        BufferedImage image = new BufferedImage(100, 30, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = image.createGraphics();
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, 100, 30);
        g.setColor(Color.BLUE);
        g.setFont(new Font("Arial", Font.BOLD, 20));
        g.drawString(captcha, 10, 20);

        // 输出图片
        response.setContentType("image/png");
        ImageIO.write(image, "png", response.getOutputStream());
    }

    private String generateRandomCode(int length) {
        String chars = "ABCDEFGHJKMNPQRSTUVWXYZ23456789";
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            sb.append(chars.charAt(random.nextInt(chars.length())));
        }
        return sb.toString();
    }
    @GetMapping("/signOut")
    public String signOut(HttpSession session,Model model){
        //清空登录账户
        session.getAttribute("loginAccount");
        session.removeAttribute("loginAccount");
        session.removeAttribute("username");
        return "catalog/main";}

    @GetMapping("/SignonForm")
    public String loginPage() {
        return "account/SignonForm";
    }

    @PostMapping("/registerForm")
    public String registerFormPost (@RequestParam("username") String username,
                                    @RequestParam("password") String password,
                                    @RequestParam("repeatedPassword")String repeatedPassword,
                                    @RequestParam("captcha") String inputCaptcha, // 新增验证码参数
                                    @RequestParam("firstname") String firstname,
                                    @RequestParam("lastname") String lastname,
                                    @RequestParam(value = "status",defaultValue = "OK") String status,
                                    @RequestParam("addr1") String addr1,
                                    @RequestParam("addr2") String addr2,
                                    @RequestParam("city") String city,
                                    @RequestParam("email") String email,
                                    @RequestParam("state") String state,
                                    @RequestParam("zip") String zip,
                                    @RequestParam("country") String country,
                                    @RequestParam("phone")String phone,
                                    @RequestParam("integer")String integer,
                                    @RequestParam("langpref")String langpref,
                                    @RequestParam(value = "favouriteCategoryId",defaultValue = "DOGS")String favouriteCategoryId,
                                    Model model,
                                    HttpSession session){

        //验证码
        String sessionCaptcha = (String) session.getAttribute("captcha");
        if (!password.equals(repeatedPassword))
        {
           model.addAttribute("error","两次密码不一致");
        } else if (password.length()<6) {
            model.addAttribute("error","密码长度需大于六位数");
        }else if (!sessionCaptcha.equals(inputCaptcha)) {
            model.addAttribute("error", "验证码错误，请重新输入验证码");
        }
        if (!password.equals(repeatedPassword)||password.length()<6||!sessionCaptcha.equals(inputCaptcha))
        {
            return "/account/RegisterForm";
        }else {
            if(accountMapper.SearchAccountCount(username)>0)
            {
                //已经存在
                model.addAttribute("error", "用户名已存在请重新输入");
                return "/account/RegisterForm";
            }
            else {
                session.removeAttribute("captcha");
                //将用户信息添加到数据库表中
                Account account=new Account();
                account.SetAccount(username,password,zip,firstname,lastname,status,addr1,addr2,city,state, Integer.valueOf(integer),country,phone,langpref,favouriteCategoryId,email);

                accountService.InsertAccount(account);
                session.setAttribute("username",username);
                session.setAttribute("loginAccount",account);
                return "catalog/main";
            }

        }

    }

    @GetMapping("/registerForm")
    public String registerForm (){
        return "/account/RegisterForm";}

    @GetMapping("/accountForm")
    public String accountForm(Account account,Model model,HttpSession session){

        if (account!=null){
            String username= (String) session.getAttribute("username");
            account=accountService.getAccount(username,session);
            accountService.ModeladdAttribute(model,account);
            return "/account/accountForm";
        }
        else{
            //......此处写错误信息
            return"/common/error";
        }
    }

    @GetMapping("ShowSnow")
    public String ShowSnow(){return "common/snow";}

    @GetMapping("/help")
    public String help(){return "../static/help";}

}